import requests
from typing import List, Optional, Dict, Any


def call_tts_api(
    text: str,
    audio_paths: List[str],
    output_file: str,
    api_url: str = "http://47.90.179.219:8501/tts_url"
) -> str:
    """
    Call TTS API to generate speech from text using specified audio prompts.
    
    Args:
        text: The text to convert to speech
        audio_paths: List of audio prompt file paths
        output_file: Path to save the generated audio file
        api_url: The TTS API endpoint URL
    
    Returns:
        str: Path to the saved audio file
    
    Raises:
        requests.RequestException: If the API call fails
    """
    headers = {
        "Content-Type": "application/json"
    }
    
    payload = {
        "text": text,
        "audio_paths": audio_paths
    }
    
    response = requests.post(api_url, headers=headers, json=payload)
    response.raise_for_status()
    
    # 直接保存音频内容到文件
    with open(output_file, 'wb') as f:
        f.write(response.content)
    
    return output_file


def generate_tts(
    text: str,
    output_file: str,
    api_url: str = "http://47.90.179.219:8501/tts_url",
    voice_type: str = "Female_SweetGirl",
    voice_mapping: Optional[Dict[str, str]] = None,
    custom_audio_paths: Optional[List[str]] = None
) -> str:
    """
    Generate TTS with predefined voice types or custom audio paths.
    
    Args:
        text: The text to convert to speech
        output_file: Path to save the generated audio file
        voice_type: Predefined voice type (default: "Female_SweetGirl")
        custom_audio_paths: Custom audio prompt paths (overrides voice_type)
    
    Returns:
        str: Path to the saved audio file
    """
    if custom_audio_paths:
        audio_paths = custom_audio_paths
    else:
        # Default audio path mapping
        if voice_mapping is None:
            voice_mapping = {
                "Female_SweetGirl": "/app/audio_prompts/磁性硬朗-男声.MP3"
            }
        
        # Get the audio path for the voice type
        if voice_type in voice_mapping:
            audio_paths = [voice_mapping[voice_type]]
        else:
            # Use the first available voice as fallback
            fallback_voice = next(iter(voice_mapping.values()))
            audio_paths = [fallback_voice]
    
    return call_tts_api(text, audio_paths, output_file, api_url)